package com.sanjishu.enterlab.electricity.sale.service;

import com.sanjishu.enterlab.electricity.sale.controller.Response;
import com.sanjishu.enterlab.electricity.sale.domain.CompanyInfo;
import com.sanjishu.enterlab.electricity.sale.domain.ContractInfo;
import com.sanjishu.enterlab.electricity.sale.domain.ContractSetting;
import com.sanjishu.enterlab.electricity.sale.domain.DetailInfo;
import com.sanjishu.enterlab.electricity.sale.mapper.CompanyInfoMapper;
import com.sanjishu.enterlab.electricity.sale.mapper.ContractInfoMapper;
import com.sanjishu.enterlab.electricity.sale.mapper.ContractSettingMapper;
import com.sanjishu.enterlab.electricity.sale.mapper.DetailInfoMapper;
import com.sanjishu.enterlab.electricity.sale.utils.Page;
import com.sanjishu.enterlab.electricity.sale.utils.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class ContractInfoService {

    @Autowired
    private ContractInfoMapper contractInfoMapper;
    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    @Autowired
    private DetailInfoMapper detailInfoMapper;
    @Autowired
    private ContractSettingMapper contractSettingMapper;
    @Value("${page.size}")
    private Integer pageSize;

    public ContractInfo findByCompanyAndTime(Integer companyInfoId) {
        return contractInfoMapper.findByCompanyAndTime(companyInfoId);
    }

    public ContractInfo findById(Integer id) {
        return contractInfoMapper.selectByPrimaryKey(id);
    }

    @Transactional
    public ContractInfo createContractInfo(Integer companyId, Integer contractInfoId, Integer types,
                                           String estElecConsumption, String description, BigDecimal longAgreementRate,
                                           BigDecimal bottomPrice, BigDecimal baseRate1,
                                           String startAt, String endedAt, String tradeCycle) throws Exception {
        CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(companyId);
        DetailInfo detailInfo = detailInfoMapper.findByCompanyId(companyId);
        ContractInfo contractInfo = null;
        Boolean isHas = true;
        if (contractInfoId != null) {
            contractInfo = contractInfoMapper.selectByPrimaryKey(contractInfoId);
        }
        if (contractInfo == null || contractInfoId == null) {
            isHas = false;
            contractInfo = new ContractInfo();
        }
        if (companyInfo != null && detailInfo != null) {
            contractInfo.setCompanyInfoId(companyId);
            contractInfo.setUserId(companyInfo.getUserId());
            contractInfo.setName(companyInfo.getName());
            contractInfo.setElecAccountNum(detailInfo.getElecAccountNum());
            contractInfo.setBankName(detailInfo.getBankName());
            contractInfo.setBankAccount(detailInfo.getBankAccount());
            contractInfo.setBankAccountName(detailInfo.getBankAccountName());
            contractInfo.setVoltageStep(detailInfo.getVoltageStep());
            contractInfo.setTransformerCapacity(detailInfo.getTransformerCapacity());
            if (estElecConsumption!= null && !estElecConsumption.equals(detailInfo.getElecConsumption())) {
                detailInfo.setElecConsumption(estElecConsumption);
                detailInfoMapper.updateByPrimaryKey(detailInfo);
                contractInfo.setElecConsumption(estElecConsumption);
            } else {
                contractInfo.setElecConsumption(detailInfo.getElecConsumption());
            }

            contractInfo.setContactName(companyInfo.getContractName());
            contractInfo.setContactPhone(companyInfo.getContractPhone());
            contractInfo.setFax(detailInfo.getFax());
            contractInfo.setAddress(companyInfo.getAddress());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (startAt != null && startAt != "") {
                contractInfo.setStartAt(sdf.parse(startAt));
            }
            if (endedAt != null && endedAt != "") {
                contractInfo.setEndedAt(sdf.parse(endedAt));
            }
            if (tradeCycle != null && tradeCycle != "") {
                contractInfo.setTradeCycle(tradeCycle);
                if (startAt == null || startAt == "" || endedAt == null || endedAt == "") {
                    int year = Calendar.getInstance().get(Calendar.YEAR) + 1;
                    String startD = year+"-01-01";
                    contractInfo.setStartAt(sdf.parse(startD));
                    String endD = year + Integer.parseInt(tradeCycle) + "-01-01";
                    contractInfo.setEndedAt(sdf.parse(endD));
                }
            } else if (startAt != null && startAt != "" && endedAt != null && endedAt != "") {
                Long diff = new Long(sdf.parse(endedAt).getTime() - sdf.parse(startAt).getTime());
                Integer year = Math.round((diff/new Long(1000*60*60*24))/new Long(30*12));
                contractInfo.setTradeCycle(year.toString());
            }
            contractInfo.setUpdateAt(new Date());
            contractInfo.setStatus(ContractInfo.STATUS_NORMAL);
            contractInfo.setPdfUrl(null);
            if (types != null) {
                contractInfo.setPlanType(types);
                if (types == 4 || types == 5) {
                    contractInfo.setPlanType(ContractInfo.PLAN_TYPE_3);
                }
            }
            if (isHas) {
                contractInfoMapper.updateByPrimaryKey(contractInfo);
            } else {
                contractInfo.setCreateAt(new Date());
                contractInfoMapper.insert(contractInfo);
            }
        }
        ContractSetting contractSetting = contractSettingMapper.findByContractId(contractInfoId);
        isHas = true;
        if (contractSetting == null) {
            isHas = false;
            contractSetting = new ContractSetting();
            contractSetting.setContractInfoId(contractInfo.getId());
        }
        if (description != null) {
            contractSetting.setDescription(description);
        }
        if (types != null) {
            if (types == ContractInfo.PLAN_TYPE_1 || types == 3) {
                contractSetting.setCooperationType(ContractSetting.TYPE_1);
            } else if (types == 4) {
                contractSetting.setCooperationType(ContractSetting.TYPE_2);
            } else if (types == 5) {
                contractSetting.setCooperationType(ContractSetting.TYPE_4);
            } else {
                contractSetting.setCooperationType(ContractSetting.TYPE_3);
            }
        }

        if (bottomPrice != null) {
            contractSetting.setBottomPrice(bottomPrice);
        }
        if (longAgreementRate != null) {
            contractSetting.setLongAgreementRate(longAgreementRate);
        }
        if (baseRate1 != null) {
            contractSetting.setBaseRate1(baseRate1);
        }
        if (estElecConsumption != null) {
            contractSetting.setEstElecConsumption(estElecConsumption);
        }
        if (isHas) {
            contractSettingMapper.updateByPrimaryKey(contractSetting);
        } else {
            contractSettingMapper.insert(contractSetting);
        }
        return contractInfo;
    }

    public Page<ContractInfo> newContractList(Integer page) {
        Long count = contractInfoMapper.countNewSetting();
        if (count == 0) {
            return new Page<ContractInfo>(new PageRequest(1, pageSize), new ArrayList<>(), count);
        }
        PageRequest request = new PageRequest(page, pageSize);
        List<ContractInfo> result = contractInfoMapper.newContractList(request);
        Page<ContractInfo> pageData = new Page<ContractInfo>(request, result, count);
        if (pageData.getCurrentPage() > pageData.getTotalPage()) {
            request = new PageRequest(pageData.getTotalPage(), pageSize);
            result = contractInfoMapper.newContractList(request);
            pageData = new Page<>(request, result, count);
        }
        return pageData;
    }

    public Page<ContractInfo> contractList(Integer page) {
        Long count = contractInfoMapper.countSetting();
        if (count == 0) {
            return new Page<ContractInfo>(new PageRequest(1, pageSize), new ArrayList<>(), count);
        }
        PageRequest request = new PageRequest(page, pageSize);
        List<ContractInfo> result = contractInfoMapper.contractList(request);
        Page<ContractInfo> pageData = new Page<ContractInfo>(request, result, count);
        if (pageData.getCurrentPage() > pageData.getTotalPage()) {
            request = new PageRequest(pageData.getTotalPage(), pageSize);
            result = contractInfoMapper.contractList(request);
            pageData = new Page<>(request, result, count);
        }
        return pageData;
    }

    @Transactional
    public Response sureSigned(Integer contractId) {
        ContractInfo contractInfo = findById(contractId);
        CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(contractInfo.getCompanyInfoId());
        if (companyInfo != null && contractInfo != null) {
            companyInfo.setStatus(CompanyInfo.STATUS_SIGNED);
            companyInfo.setUpdatedAt(new Date());
            companyInfoMapper.updateByPrimaryKey(companyInfo);
            contractInfo.setStatus(ContractInfo.STATUS_SIGNED);
            contractInfo.setUpdateAt(new Date());
            contractInfoMapper.updateByPrimaryKey(contractInfo);
            return Response.buildSuccess("操作成功。");
        } else {
            return Response.getError("操作失败，请重新尝试。");
        }
    }


    public void updateBoundStatus(Integer contractInfoId, Integer boundStatus) {
        ContractInfo contractInfo = findById(contractInfoId);
        contractInfo.setBoundStatus(boundStatus);
        contractInfoMapper.updateByPrimaryKey(contractInfo);
    }

    public Page<ContractInfo> listByBoundStatus(Integer boundStatus, Integer page) {
        Long count = contractInfoMapper.countByBoundStatus(boundStatus);
        if (count == 0) {
            return new Page<ContractInfo>(new PageRequest(1, pageSize), new ArrayList<>(), count);
        }
        PageRequest request = new PageRequest(page, pageSize);
        List<ContractInfo> result = contractInfoMapper.listByBoundStatus(boundStatus);
        Page<ContractInfo> pageData = new Page<ContractInfo>(request, result, count);
        if (pageData.getCurrentPage() > pageData.getTotalPage()) {
            request = new PageRequest(pageData.getTotalPage(), pageSize);
            result = contractInfoMapper.listByBoundStatus(boundStatus);
            pageData = new Page<>(request, result, count);
        }
        return pageData;
    }

}
